import 'dart:io';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';

/// 延迟加载的视频播放器组件
/// 用于详情页面，只在真正需要时才初始化视频播放器
class LazyVideoPlayerWidget extends StatefulWidget {
  final String videoPath;
  final double? width;
  final double? height;
  final bool autoPlay;
  final bool looping;
  final bool showControls;

  const LazyVideoPlayerWidget({
    super.key,
    required this.videoPath,
    this.width,
    this.height,
    this.autoPlay = false,
    this.looping = false,
    this.showControls = true,
  });

  @override
  State<LazyVideoPlayerWidget> createState() => _LazyVideoPlayerWidgetState();
}

class _LazyVideoPlayerWidgetState extends State<LazyVideoPlayerWidget> {
  VideoPlayerController? _videoPlayerController;
  ChewieController? _chewieController;
  bool _isInitialized = false;
  bool _hasError = false;
  bool _isLoading = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    // 延迟初始化，避免页面打开时的卡顿
    Future.delayed(const Duration(milliseconds: 200), () {
      if (mounted) {
        _initializePlayer();
      }
    });
  }

  Future<void> _initializePlayer() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
      _hasError = false;
    });

    try {
      // 检查视频源类型并创建对应的控制器
      if (widget.videoPath.startsWith('http')) {
        // 网络视频
        _videoPlayerController = VideoPlayerController.networkUrl(
          Uri.parse(widget.videoPath),
        );
      } else if (widget.videoPath.startsWith('/') ||
          widget.videoPath.contains('\\') ||
          widget.videoPath.startsWith('file://')) {
        // 设备本地文件
        String filePath = widget.videoPath;
        if (filePath.startsWith('file://')) {
          filePath = filePath.substring(7); // 移除 file:// 前缀
        }
        _videoPlayerController = VideoPlayerController.file(File(filePath));
      } else {
        // 应用资源文件
        _videoPlayerController = VideoPlayerController.asset(widget.videoPath);
      }

      await _videoPlayerController!.initialize();

      _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController!,
        autoPlay: widget.autoPlay,
        looping: widget.looping,
        showControls: widget.showControls,
        aspectRatio: _videoPlayerController!.value.aspectRatio,
        placeholder: _buildPlaceholder(),
        errorBuilder: (context, errorMessage) {
          return _buildErrorWidget(errorMessage);
        },
      );

      if (mounted) {
        setState(() {
          _isInitialized = true;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
          _errorMessage = e.toString();
        });
      }
    }
  }

  Widget _buildPlaceholder() {
    return Container(
      color: Colors.black,
      child: Stack(
        children: [
          // 显示回退图片
          Container(
            decoration: BoxDecoration(
              // image: DecorationImage(
              //   image: AssetImage(widget.fallbackImage!),
              //   fit: BoxFit.cover,
              // ),
            ),
          ),
          // 加载指示器
          const Center(child: CircularProgressIndicator(color: Colors.white)),
        ],
      ),
    );
  }

  Widget _buildErrorWidget(String errorMessage) {
    return Container(
      color: Colors.black,
      child: Stack(
        children: [
          // 显示回退图片
          Container(
            decoration: BoxDecoration(
              // image: DecorationImage(
              //   image: AssetImage(widget.fallbackImage!),
              //   fit: BoxFit.cover,
              // ),
            ),
          ),
          // 错误信息
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, color: Colors.white, size: 48.sp),
                SizedBox(height: 16.h),
                Text(
                  '视频加载失败',
                  style: TextStyle(color: Colors.white, fontSize: 16.sp),
                ),
                SizedBox(height: 8.h),
                Text(
                  errorMessage,
                  style: TextStyle(color: Colors.white70, fontSize: 12.sp),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _chewieController?.dispose();
    _videoPlayerController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 如果出错，显示错误界面
    if (_hasError) {
      return Container(
        width: widget.width,
        height: widget.height,
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: _buildErrorWidget(_errorMessage ?? '未知错误'),
      );
    }

    // 如果还在加载或未初始化，显示占位符
    if (_isLoading || !_isInitialized || _chewieController == null) {
      return Container(
        width: widget.width,
        height: widget.height,
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: _buildPlaceholder(),
      );
    }

    // 显示视频播放器
    return Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.r)),
      clipBehavior: Clip.hardEdge,
      child: Chewie(controller: _chewieController!),
    );
  }
}
